package pers.qianyu.month_202012.date_20201220;

import java.util.*;

/**
 * 442. 数组中重复的数据
 * https://leetcode-cn.com/problems/find-all-duplicates-in-an-array/
 *
 * @author mizzle rain
 * @date 2020-12-20 16:00
 */
public class FindDuplicates {
    // 哈希表计数
    public List<Integer> findDuplicates(int[] nums) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }
        ArrayList<Integer> res = new ArrayList<>();
        for (Integer k : map.keySet()) {
            Integer v = map.get(k);
            if (v == 2) {
                res.add(k);
            }
        }
        return res;
    }

    // 原地修改，负数标记
    public List<Integer> findDuplicates2(int[] nums) {
        ArrayList<Integer> res = new ArrayList<>();
        for (int num : nums) {
            int index = Math.abs(num) - 1;
            if (nums[index] > 0) {
                nums[index] = -nums[index];
            } else {
                // 说明标记过
                res.add(index + 1);
            }
        }
        return res;
    }
}
